<template>
  <view>
    <u-sticky>
      <view class="header card" id="header">
        <view class="title">设备当前运行状态</view>
        <view class="u-flex u-row-between u-m-t-30">
          <view class="title" style="width: 70%">
            <text>
              {{device.alias? device.alias+'号_':''}}{{device.deviceTypeName}}
              <template v-if="device.deviceNo">_<text>{{device.deviceNo}}</text></template>{{device.remarkName?'_'+device.remarkName:''}}
            </text>
          </view>
          <view class="u-flex-center">
            <view :class="device.networkIntensity>5?'online':'offLine'">{{device.networkIntensity>5?'在线':'离线'}}</view>
            <signal :level="device.networkIntensity>5?onLine:offLine"></signal>
          </view>
        </view>
      </view>
    </u-sticky>
    <view class="warp">
      <scroll-view :style="{ height: height + 'px' }" scroll-y="true" :scroll-with-animation="true" :enable-back-to-top="true" @scrolltolower="reachBottom">
        <view class="body card" v-if="list.length > 0">
          <view class="title">运行设备记录</view>
          <view v-for="(item, index) in list" :key="index">
            <view class="u-flex u-row-between u-m-t-25">
              <view class="one-online">
                {{item.timeDifference}}
              </view>
              <view class="u-flex-center">
                <view :class="item.type==1?'online':'offLine'">{{item.type==1?'在线':'离线'}}</view>
                <signal :level="item.type==1?onLine:offLine"></signal>
              </view>
            </view>
            <view class="date">{{$u.timeFormat(Date.parse(item.startTime), 'yyyy-mm-dd hh:MM:ss') }}</view>
            <u-line v-if="list.length-1 != index" color="rgba(34, 34, 34, 0.2)" margin="20rpx 0rpx"></u-line>
          </view>
        </view>
        <u-loadmore :status="loadStatus" height="70rpx" line=true></u-loadmore>
      </scroll-view>
    </view>
  </view>
</template>

<script>
import signal from '@/components/signal/signal.vue'
	export default {
    components: {
      signal,
    },
		data() {
			return {
        onLine:30,
        offLine:0,
        height:0,
        params:{
          id:'',
          deviceNo:'',
          pageNum: 1,
          pageSize: 10,
          totalPage: 1,
        },
        list:[],
        device: {
          id: '',
          alias: '',
          deviceNo: '',
          storeName: '',
          rateEach: '',
          goodsStockVoList: [],
          remarkName: '',
          deviceTypeName: '',
          giftType: 1,
          totalNumberPosition: 0,
          measuringUnit: '',
          bindGoodsTitle: '',
          status: '',
        },
        loadStatus:'nomore',
			};
		},
    onReady() {
      this.getPomHeight();
    },
    onLoad(options){
      // console.log(options,'option')
      if (options.id) {
        this.params.id = options.id;
        this.findOneDeviceById();
      }
    },
    // 下拉事件
    onPullDownRefresh() {
      this.load()
    },
    methods: {
      load() {
        this.list = [];
        this.params.pageNum = 1;
        this.params.totalPage = 1;
        this.findOneDeviceById();
        this.deviceOnlineOfflineByDeviceNoList()
        console.log("进入了吗",this.list.length)
      },
      findOneDeviceById() {
        uni.showLoading({
          title: '加载中...',
          mask: true
        })
        let param = {
          id: this.params.id,
        }
        this.$api('device.findOneDeviceById', param)
            .then(res => {
              uni.hideLoading();
              if (res.status == 0) {
                this.device = res.data;
                // console.log(this.device,'device')
                this.deviceOnlineOfflineByDeviceNoList();
              } else {
                this.$helpers.toast('请求数据失败:' + res.msg);
              }
            })
            .catch(() => {
              uni.stopPullDownRefresh();
              uni.hideLoading();
            });
      },
      deviceOnlineOfflineByDeviceNoList(){
        if(this.device.deviceNo == null || this.device.deviceNo == ''){
          this.$helpers.toast('设备号不能为空');
          return;
        }
        this.params.deviceNo = this.device.deviceNo
        this.$api('deviceOnlineOfflineRecord.deviceOnlineOfflineList', this.params) .then(res => {
              if (res.status == 0) {
                this.params.pageNum = res.data.pageNum;
                this.params.totalPage = res.data.pages;
                // console.log("this.params.totalPage",this.params.totalPage )
                this.loadStatus = res.data.pageNum === res.data.pages ? 'nomore' : 'loadmore';
                if (this.params.totalPage == 0) {
                  this.loadStatus = 'nomore';
                }
                this.list = [...this.list, ...res.data.list]; //合并数组
                for (let i = 0; i < this.list.length; i++) {
                  let timeDifference = this.calculateTimeDifference(this.list[i].startTime, this.list[i].endTime, this.list[i].type, i);
                  this.list[i].timeDifference = timeDifference;
                }
              } else {
                this.$helpers.toast('请求数据失败:' + res.msg);
              }
            })
            .catch(() => {

            });
      },
      calculateTimeDifference(startTime, endTime, type, index) {
        if(index > 0 && endTime == null){
          return '';
        }
        // if(this.pageHelper.currentPage > 1 && endTime == null){
        //   return '';
        // }
        var startDate = new Date(startTime);
        var endDate = null;
        if(endTime == null || endTime == ''){
          endDate = new Date();
        }else{
          endDate = new Date(endTime);
        }
        var timeDiff = Math.abs(endDate.getTime() - startDate.getTime());

        var years = Math.floor(timeDiff / (1000 * 60 * 60 * 24 * 365));
        var months = Math.floor((timeDiff % (1000 * 60 * 60 * 24 * 365)) / (1000 * 60 * 60 * 24 * 30));
        var days = Math.floor((timeDiff % (1000 * 60 * 60 * 24 * 30)) / (1000 * 60 * 60 * 24));
        var hours = Math.floor((timeDiff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((timeDiff % (1000 * 60)) / 1000);

        let name = '';
        if(type == 1){
          name += '在线时长';
        }else{
          name += '离线时长';
        }
        if(years > 0){
          name += years + '年';
        }
        if(months > 0){
          name+= months + '个月';
        }
        if(days > 0){
          name += days + '天';
        }
        if(hours > 0){
          name += hours + '小时';
        }
        if(minutes > 0){
          name += minutes + '分';
        }
        if(seconds > 0){
          name += seconds + '秒';
        }
        return name;
      },
      //加载更多
      reachBottom() {
        if (this.params.pageNum >= this.params.totalPage) {
          return;
        }
        this.params.pageNum++;
        // console.log("到底部了:", this.params.pageNum);
        this.loadStatus = 'loading'
        this.deviceOnlineOfflineByDeviceNoList();
      },
      // 获取各个盒子的高度
      getPomHeight() {
        let query = wx.createSelectorQuery().in(this)
        query.select('#header').boundingClientRect()
        query.exec(res => {
          let windowHeight = wx.getSystemInfoSync().windowHeight
          this.height = windowHeight -26
          for (let i = 0; i < res.length; i++) {
            this.height -= res[i].height;
          }
        })
      }
    }
	}
</script>

<style lang="scss" scoped>
  .header{
    margin: 26rpx;
    .signal{
      display: flex;
      align-items: flex-end;
      position: relative;
      .item {
        margin-left: 6rpx;
        width: 4rpx;
        background-color: #999;
      }
    }
  }
  .online{
    color: rgb(7, 213, 176);
    font-size: 28rpx;
    padding-right: 10rpx;
    margin-top: 8rpx;
  }
  .offLine{
    color: red;
    font-size: 28rpx;
    padding-right: 10rpx;
    margin-top: 8rpx;
  }
  .title{
    color: #000000;
    font-size: 30rpx;
  }
  .card{
    border-radius: 25rpx;
    background: white;
    padding: 26rpx;
  }
	.warp{
		margin: 26rpx;

	  .body{
      .one-online{
        font-size: 28rpx;
        color: rgba(0,0,0,0.8);
      }
      .date{
        color: rgba(0,0,0,0.5);
        font-size: 26rpx;
        margin-top: 10rpx;
      }
    }
  }
</style>
